<script lang="ts" setup name="home">
import { useRouter } from "vue-router";
import EventAdvertising from "@/components/HYHome/eventAdvertising.vue";
import GameList from "@/components/HYHome/gameList.vue";
import TopPublicizeApp from "@/components/HYHome/topPublicizeApp.vue";
import BottomHome from "@/components/HYHome/bottomHome.vue";
import BottomPublicizeInfo from "@/components/HYHome/bottomPublicizeInfo.vue";
import SidebarHome from "@/components/HYHome/sidebarHome.vue";
import SiderBottom from "@/components/HYHome/siderBottom.vue";
import GameOperatorsList from "@/components/HYHome/gameOperatorsList.vue";
import GamePage from "@/components/HYHome/gamePage.vue";
import InitialRecharge from "@/components/HYHome/initialRecharge.vue";
import DownloadPage from "@/components/HYHome/downloadPage.vue";
import MoneyRain from "@/components/Activit/distriAgent/moneyRain.vue";
import FirstAid from "@/components/HYHome/firstAid.vue";
import DownPwaAndApk from "@/components/DownPwaAndApk/index.vue";
//import TreasureChestPoster from "@/components/Activit/distriAgent/treasureChestPoster.vue";
import UpdateOverlay from "@/components/HYHome/updateOverlay.vue";
import { RouterEnums } from "@/types";
import { UserStore } from "@/store";
import Pubsub from "pubsub-js";
import { PubSubEnum } from "@/types";
import { HomeAxios } from "@/api";
import {
  ref,
  onMounted,
  onBeforeMount,
  onBeforeUnmount,
  onActivated,
  onDeactivated,
  nextTick,
} from "vue";
import { FiltrationFun } from "@/utils";
import { UAParser } from "ua-parser-js";
import moment from "moment";
const parser = new UAParser(navigator.userAgent);
console.log("parser=======", parser.getOS());
defineOptions({
  name: "home",
});
const router = useRouter();
const userStore = UserStore();
const RefSidebar = ref();
const RefBottom = ref();

//openPageType用于判断是打开游戏页面还是下载页面：0游戏页面,1下载apk页面
const openPageType = ref(0);
//是用来判断pwa环境点击下载的时候打开新页面
const sdmode = ref(0);
const advid = ref("");
onBeforeMount(() => {
  // const os = parser.getOS().name + " " + parser.getOS().version;
  //是不是在pwa或者apk环境
  if (FiltrationFun.detectEnvironment() === "pwa" || FiltrationFun.detectEnvironment() === "apk") {
    fillType.value = false;
  }
  //获取推广渠道advId和推荐人的a
  const shareUrl = router.options.history.state.current as string;
  const arrShareUrl = parseQueryString(shareUrl);
  if (arrShareUrl.length > 0) {
    for (let i = 0; i < arrShareUrl.length; i++) {
      // if (arrShareUrl[i].a) {
      //   sessionStorage.setItem("linkId", arrShareUrl[i].a);
      // }
      if (arrShareUrl[i].ch) {
        advid.value = arrShareUrl[i].ch;
        //点击访问的回传事件
        FiltrationFun.setReportEvent("ViewContent");
        //sessionStorage.setItem("advid", arrShareUrl[i].ch);
      }
      //用于判断是不是打开头部广告栏
      if (arrShareUrl[i].sdmode) {
        sdmode.value = arrShareUrl[i].sdmode;
        fillType.value = false;
      }
    }
    //判断网站是否绑定要打开仿谷歌页面的参数
    const keysToCheck = ["ch", "sdmode", "fbPixelId"];
    const result = keysToCheck.every(key => arrShareUrl.some(obj => obj.hasOwnProperty(key)));
    if (result) {
      openPageType.value = 1;
    }
  }
});
const scrollTop = ref(0);
const propsOverlayShow = ref(false);
onActivated(() => {
  const getCollect = localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid);
  console.log("首页的onActivated", JSON.parse(getCollect as string));
  //判断打开红包雨弹窗和关闭左侧页面
  if (localStorage.getItem("openSidebar") == null) {
    propsOverlayShow.value = false;
  } else {
    propsOverlayShow.value = true;
  }
  if (userStore.isLogin && openPageType.value == 0) {
    //查询用户余额；
    checkBalance();
    //Pubsub.publish(PubSubEnum.UPDATE_USERINFO);
  }
  if (userStore.isLogin) {
    //获取通知的个数
    getMsgNoticeNum();
  }
  //回到可视区域
  nextTick(() => {
    const container = document.querySelector(".content-frame");
    if (container) {
      container.scrollTop = scrollTop.value;
    }
  });
});
onMounted(async () => {
  console.log("Home首页的onMounted");
  nextTick(() => {
    const container = document.querySelector(".content-frame");
    if (container) {
      container.addEventListener("scroll", () => {
        scrollTop.value = container.scrollTop;
      });
    }
  });
  //获取推广渠道advId和推荐人的a
  const timeoutData = setTimeout(() => {
    const shareUrl = router.options.history.state.current as string;
    const arrShareUrl = FiltrationFun.parseQueryString(shareUrl);
    if (arrShareUrl.length > 0) {
      for (let i = 0; i < arrShareUrl.length; i++) {
        if (arrShareUrl[i].a) {
          sessionStorage.setItem("linkId", arrShareUrl[i].a);
        }
        if (arrShareUrl[i].ch) {
          sessionStorage.setItem("advid", arrShareUrl[i].ch);
        }
      }
    }
    clearTimeout(timeoutData);
  }, 2000);

  // if (userStore.isLogin && openPageType.value == 0) {
  //   //查询用户余额；
  //   checkBalance();
  //   Pubsub.publish(PubSubEnum.UPDATE_USERINFO);
  // }
  if (userStore.isLogin) {
    //获取通知的个数
    // getMsgNoticeNum();
    //获取下载pwa和apk下载的奖励
    receivePwaReward();
    //获取安装引导配置
    //getInstallGuideConfig()
  }
  //获取主页媒体配置列表
  getMediaConfigList();
  if (window.matchMedia("(display-mode: standalone)").matches) {
    console.log("PWA 已安装并以独立应用模式运行");
  } else {
    console.log("PWA 未安装");
  }
});
function parseQueryString(queryString) {
  const queryPart = queryString.split("?")[1] || "";
  const urlParams = new URLSearchParams(queryPart);
  const paramsArray: any = [];
  urlParams.forEach((value, key) => {
    paramsArray.push({ [key]: value });
  });

  return paramsArray;
}

/****************打开左侧的弹窗********************* */
const clickOpenSidebar = () => {
  RefSidebar.value.setSidebar();
  localStorage.setItem("openSidebar", "true");
};
//打开游戏运营商的列表
const RefOperators = ref();
//const providerId = ref(0);
//打开游戏列表页面
const openOperatorsList = e => {
  RefOperators.value.opneRightPopup();
  //RefOperators.value.getGameList();
  console.log("没有错啊", e.groupId);
  groupId.value = e.groupId;
};
//打开游戏链接界面和传游戏url
const RefGamePage = ref();
const intervalData = ref();
const openGameUrl = e => {
  clearInterval(intervalData.value);
  intervalData.value = null;
  gameUrl.value = e;
  RefGamePage.value.showModal();
};
//判断说关闭头部下载框状态
const fillType = ref(true);
const clickTopAdvertise = () => {
  fillType.value = false;
};
const gameUrl = ref("");
/*******打开首充的页面***********/
const refInitialRecharge = ref();
const openActfirst = () => {
  refInitialRecharge.value.openActfirst();
};
const message = ref();
const openMessageDetail = (value: string) => {
  message.value = value;
  RefBottom.value.setSidebar();
};
const closeBottomMessage = () => {
  RefBottom.value.closeSidebar();
};
const groupId = ref(0);
//打开游戏列表页面
const openGamePageList = e => {
  RefOperators.value.opneRightPopup();
  //RefOperators.value.getGameList();
  groupId.value = e;
};
const RefGameList = ref();
//关闭页面就刷新
const refreshpage = () => {
  RefGameList.value.refreshGameList();
};
const leftBanner = ref([]);
//左边侧边栏Banner数据
const leftBannerFun = e => {
  if (e) {
    leftBanner.value = e;
  }
};
//关闭游戏页面调用的
const closurePageGame = async () => {
  //查询用户余额；
  //await userStore.getBalance();
  checkBalance();
};
const refFirstAid = ref();
//打开客服页面
const clickOpenFirstAid = () => {
  refFirstAid.value.openActfirst();
};
//获取主页媒体配置列表
const mediaList: any = ref([]);
const mediaSetting: any = ref([]);
const getMediaConfigList = () => {
  HomeAxios.getMediaConfigList().then(res => {
    mediaList.value = res.list;
    mediaSetting.value = res.list.filter(item => item.isSetting === 1);
  });
};
//打开主页媒体配置
const openLink = item => {
  if (item.mediaLink && item.mediaLink !== "") {
    window.open(item.mediaLink);
  }
};
//1不可安装提示安装的图片，2就是可以安装的
const donwType = ref(1);
const DownPwaAndApkRef = ref();
//点击下载的apk和pwa的
const donwFum = e => {
  donwType.value = e;
  DownPwaAndApkRef.value.closefun();
};

//获取消息通知个数
const msgNum = ref(0);
const getMsgNoticeNum = () => {
  HomeAxios.getMsgNoticeNum().then(res => {
    msgNum.value = res.total;
  });
};
//领取奖励pwa
const receivePwaReward = () => {
  if (FiltrationFun.detectEnvironment() == "pwa" || window["hy_is_apk"] !== undefined) {
    // const os = parser.getOS().name + " " + parser.getOS().version;
    const type = FiltrationFun.detectEnvironment() === "pwa" ? 0 : 1;
    const deviceUniqueKeyId = {
      id: "",
    };
    if (
      !localStorage.getItem("deviceUniqueKey") ||
      localStorage.getItem("deviceUniqueKey") === "" ||
      localStorage.getItem("deviceUniqueKey") === null
    ) {
      const deviceList = ["hy", FiltrationFun.randomizedString(), moment().valueOf(), "hy"];
      const deviceUnique = deviceList.join("-"); // 生成浏览器指纹
      deviceUniqueKeyId.id = deviceUnique;
      localStorage.setItem("deviceUniqueKey", deviceUnique);
    } else {
      deviceUniqueKeyId.id = localStorage.getItem("deviceUniqueKey") as string;
    }
    HomeAxios.getReceivePwaReward({
      mac: deviceUniqueKeyId.id,
      type: type,
    }).then(res => {
      console.log("pwa和apk奖励获取成功了吗", res);
    });
  }
};
const MoneyRainRef: any = ref(null);
//打开红包雨活动
const openMoneyRain = () => {
  if (MoneyRainRef.value != null) {
    MoneyRainRef.value.openMoneyRain();
  }
};

//获取安装引导配置
// const getInstallGuideConfig=()=>{
//   const uid=userStore.userInfoDetails.account.uid;
//   HomeAxios.getInstallGuideConfig({advStr:advid.value,uid:uid}).then(res=>{
//     console.log("获取安装引导配置",res);
//   })
// }
//查询余额
const checkBalance = () => {
  if (userStore.isLogin && openPageType.value == 0) {
    //查询用户余额；
    intervalData.value = setInterval(async () => {
      if (userStore.isLogin) {
        await userStore.getBalance().catch(() => {
          clearInterval(intervalData.value);
          intervalData.value = null;
        });
      } else {
        clearInterval(intervalData.value);
        intervalData.value = null;
      }
    }, 2000);
    Pubsub.publish(PubSubEnum.UPDATE_USERINFO);
  }
};
//销毁查询用户金额的定时器
onBeforeUnmount(() => {
  console.log("Home页面即将被毁onBeforeUnmount");
  clearInterval(intervalData.value);
});
//缓存页面的离开的
onDeactivated(() => {
  clearInterval(intervalData.value);
  intervalData.value = null;
});
const floatIconList: any = ref([]);
//获取浮动图标
const getFloatIconList = e => {
  floatIconList.value = e;
};
//广播下面的活动跳转
const gotoActPage = actTypeId => {
  // 1=vip 2=救济金 3=宝箱 4=首充，5=代理返现 6=无限代理 7=等级活动 8=充值赠送 9=红包雨活动 10 = 全局自助打码 11=超级会员日活动 13 pwa安装奖励
  if (actTypeId === 1) {
    //VIP会员
    router.push(RouterEnums.ACTVIP);
  } else if (actTypeId === 2) {
    //救济金
    router.push(RouterEnums.ACTRELIEF);
  } else if (actTypeId === 3) {
    //宝箱
    router.push(RouterEnums.TREASUREChEST);
  } else if (actTypeId === 4) {
    openActfirst();
  } else if (actTypeId === 6) {
    //无限代理==直属代理
    router.push(RouterEnums.DISTRIAGENT);
  } else if (actTypeId === 7) {
    //等级活动
    router.push(RouterEnums.LEVELREWARDSPAGE);
  } else if (actTypeId === 9) {
    //红包雨
    openMoneyRain();
  } else if (actTypeId === 10) {
    //10 = 全局自助打码
    router.push(RouterEnums.WEBSITEREBATES);
  } else if (actTypeId === 11) {
    //11 = 超级会员日活动
    router.push(RouterEnums.SIPERMEMBERDAY);
  }
};
//获取 弹窗的popBanner图
const popBanner = ref([]);
const popBannerFun = e => {
  popBanner.value = e;
};
</script>

<template>
  <div class="page-frame">
    <div class="game-page-frame" v-if="openPageType === 0">
      <div class="frame-div">
        <div :class="[fillType ? 'fill-frame' : 'fill-frame2']"></div>
        <!-- 头部广告位app下载 网站信息及消息，目录列表，客服-->
        <TopPublicizeApp
          :msgNum="msgNum"
          :sdmode="sdmode"
          @open-sidebar="clickOpenSidebar"
          @click-top-advertise="clickTopAdvertise"
          @openFirstAid="clickOpenFirstAid"
          @donwFum="donwFum"
        />
        <div class="content-frame">
          <!-- 活动广告轮播图 -->
          <EventAdvertising
            :advid="advid"
            @open-bottom="openMessageDetail"
            @close-bottom-message="closeBottomMessage"
            @left-banner-fun="leftBannerFun"
            @openMoneyRain="openMoneyRain"
            @getFloatIconList="getFloatIconList"
            @popBannerFun="popBannerFun"
          />
          <!-- <div class="add-frame" @click="promptUser">添加到主屏幕</div> -->
          <!--游戏代理商列表 -->

          <GameList
            ref="RefGameList"
            @open-operators-list="openOperatorsList"
            @open-game-url="openGameUrl"
            @openGamePageList="openGamePageList"
          />
          <!-- 底部公告说明宣传 -->
          <BottomPublicizeInfo :mediaList="mediaList" @donwFum="donwFum" />
        </div>
        <!-- 底部跳转登录注册及用户余额 -->
        <BottomHome />
      </div>
      <!-- 左边侧边栏 用户中心-->
      <SidebarHome
        ref="RefSidebar"
        :leftBanner="leftBanner"
        @openFirstAid="clickOpenFirstAid"
        :mediaList="mediaList"
        :propsOverlayShow="propsOverlayShow"
      />
      <!-- 底部消息详情-->
      <SiderBottom ref="RefBottom" :message-content="message" />
      <!-- 右边游戏厂商的游戏列表 -->
      <GameOperatorsList
        ref="RefOperators"
        :listIndex="groupId"
        @open-game-url="openGameUrl"
        @closurePopup="refreshpage"
      />
      <!-- 打开游戏页面 -->
      <GamePage ref="RefGamePage" :game-url="gameUrl" @closurePageGame="closurePageGame" />
      <!-- 右下角的浮标 -->
      <div class="activity-frame df fw-wr" v-if="floatIconList.length > 0">
        <!-- <img src="@/image/new_img/home/activity_bottom.png" @click="openActfirst" />
        <img
          src="@/image/new_img/home/acting-img.png"
          @click="router.push(RouterEnums.DISTRIAGENT)"
        /> -->
        <img
          v-for="(item, index) in floatIconList"
          :src="item.floatIcon"
          :key="index"
          @click="gotoActPage(item.actType)"
        />
      </div>
      <!-- 底部分享的浮标 -->
      <img
        class="share-tons-frame"
        v-if="mediaSetting.length > 0"
        :src="
          mediaSetting[0].customBuoy === ''
            ? mediaSetting[0].defaultBuoy
            : mediaSetting[0].customBuoy
        "
        @click="openLink(mediaSetting[0])"
      />
      <div></div>
      <!-- 首充活动 -->
      <InitialRecharge ref="refInitialRecharge" />
      <!-- 现金雨页面 -->
      <MoneyRain ref="MoneyRainRef" />
      <!-- 客服 -->
      <FirstAid ref="refFirstAid" />
      <!-- 点击下载pwa和apk页面 -->
      <DownPwaAndApk ref="DownPwaAndApkRef" />
      <!-- 弹窗活动的组件数据从轮播图来-->
      <!-- <TreasureChestPoster :popBanner="popBanner" /> -->
      <!-- 更新的弹窗 -->
      <UpdateOverlay :advid="advid" @openFirstAid="clickOpenFirstAid" />
    </div>

    <div v-else class="game-page-frame">
      <!-- 游戏下载页面 -->
      <DownloadPage />
    </div>
  </div>
</template>
<style lang="less" scoped>
.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 每列的宽度相等 */
  grid-gap: 10px; /* 格子之间的间隙 */
  /* 如果你想要不同的列宽，可以这样设置：
     grid-template-columns: 1fr 2fr 1fr; */
}

.item {
  background-color: #f2f2f2; /* 格子的背景色 */
  border: 1px solid #ddd; /* 格子的边框 */
  padding: 20px; /* 格子的内边距 */
}

.add-frame {
  width: 100%;
  height: 50px;
  border-radius: 28px;
  border: 1px solid red;
  font-size: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-frame {
  width: 100%;
  height: 100%;
  max-width: 750px;
  overflow: hidden;
  // position: relative;
  // left: 0;
  // top: 0;
  .game-page-frame {
    width: 100%;
    height: 100%;
  }
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .fill-frame {
    width: 100%;
    height: 205px;
  }

  .fill-frame2 {
    width: 100%;
    height: 100px;
  }

  .frame-div {
    width: 100%;
    height: 100%;
    // background-image: url(@/image/new_img/main_bg_2.png);
    background-size: cover;
    background-repeat: repeat;
    position: relative;
    left: 0;
    top: 0;
    overflow: hidden;
    .top-spread-frame {
      width: 100%;
      background-image: url(@/image/new_img/home/home_download_bg.png);
      background-size: 100% 100%;
      object-fit: cover;
      height: 68.3594px;

      .close-bai-img {
        width: 23.9688px;
        height: 23.9688px;
        margin-left: 18px;
      }

      .ome_download_text-img {
        width: 271.984px;
        height: 59.3438px;
        margin-left: 20px;
      }

      .right-frame {
        font-size: 16px;
        width: 109px;
        height: 43.5938px;
        background: #0652bc;
        color: #ffffff;
        margin-right: 21px;
        border-radius: 10px;
      }
    }
  }

  .content-frame {
    width: 100%;
    height: calc(100% - 280px);
    margin: auto;
    overflow-x: hidden;
    overflow-y: scroll;
    padding-bottom: 20px;
    max-height: 100%; /* 确保它的高度是可滚动的 */
    //padding-left: 27.35px;
    .app-name-frame {
      width: 100%;
      height: 81.8906px;

      .directory-frame {
        margin-left: 29.25px;
        width: auto;
        height: auto;

        .website-address {
          width: 137.891px;
          height: 38.6094px;
          margin-left: 10px;
        }
      }
    }
  }

  .directory-img {
    width: 64.9219px;
    height: 64.9219px;
  }

  .margins-interval {
    margin-left: 10px;
    margin-right: 29.25px;
  }
}

.frame-div::-webkit-scrollbar {
  display: none;
}

content-frame::-webkit-scrollbar {
  display: none;
}

.activity-frame {
  width: 133.5px;
  height: auto;
  position: fixed;
  right: 0;
  bottom: 195px;
  z-index: 90;
  img {
    width: 133.5px;
    height: 133.5px;
    margin-top: 40px;
  }
}
.activity-bottom-frame {
  bottom: 360px;
}
.share-tons-frame {
  width: 132px;
  height: 132px;
  position: fixed;
  left: 0;
  bottom: 195px;
  z-index: 90;
}

.swiper-block-wrapper {
  --swiper-pagination-color: #fff;
  /* 两种都可以 */
}
</style>
